<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Services\System\File;
use Faker\Provider\Base;
use Illuminate\Http\Request;

/**
 * 系统文件控制器
 * @package App\Http\Controllers\Admin
 */
class SysFileController extends Controller
{
    use ApiResponse;

    private $sysFileSer;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->sysFileSer = new File();
    }

    /**
     * 文件列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $typeList = $this->sysFileSer->getTypeList();
        $pageSize = $request->get('pageSize', 10);
        $query = \App\Models\System\File::query()->select('*');
        $fileType = $request->get('fileType', '');
        if ($fileType) {
            $query->where('file_type', $fileType);
        }
        //搜索关键字
        $keyword = $request->get('keyword', '');
        if ($keyword) {
            $query->where('origin_name', 'like', '%' . $keyword . '%');
        }
        //时间范围
        $timeArea = $request->get('timeArea', []);
        $startTime = !empty($timeArea[0]) ? strtotime($timeArea[0]) : 0;
        $endTime = !empty($timeArea[1]) ? strtotime($timeArea[1]) : 0;
        if (!empty($startTime) && !empty($endTime)) {
            $query->whereBetween('created_at', [$startTime, $endTime]);
        } elseif (!empty($startTime) && empty($endTime)) {
            $query->whereRaw("created_at >= '" . $startTime . "'");
        } elseif (empty($startTime) && !empty($endTime)) {
            $query->whereRaw("created_at <= '" . $endTime . "'");
        }
        $query->orderByDesc('file_id');
        $rows = $query->paginate($pageSize, ['*'], 'pageNo');
        if ($rows->isNotEmpty()) {
            foreach ($rows as $k => $row) {
                $row['file_type_str'] = isset($typeList[$row['file_type']]) ? $typeList[$row['file_type']] : '未知';
                $rows[$k] = $row;
            }
        }
        return $this->success('加载成功', [
            'list' => $rows->items(),
            'total' => $rows->total(),
            'pageNo' => $rows->currentPage(),
            'typeList' => $typeList
        ]);
    }
}
